import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/api/bean.dart';
import 'package:study_demo/base/BaseController.dart';

import '../../generated/assets.dart';
import '../../util/commond.dart';
import '../../util/utils.dart';

class ApiQueryController extends BaseController {
  final codes = <ApiCode>[].obs;

  List<ApiCode> allCodes = <ApiCode>[];

  TextEditingController _textEditingController = TextEditingController();

  TextEditingController get textEditingController => _textEditingController;

  @override
  Future<void> onInit() async {
    super.onInit();
    var content = await loadAsset(Assets.fileYzGoApi);
    List<dynamic> codeList =
        json.decode(content).map((e) => ApiCode.fromJson(e)).toList();
    codes.assignAll(List<ApiCode>.from(codeList));
    allCodes = List<ApiCode>.from(codeList);

    _textEditingController.addListener(() {
      if (_textEditingController.text.isEmpty) {
        codes.assignAll(allCodes);
      }
    });
  }

  search() {
    String content = _textEditingController.text.toString().trim();
    codes.clear();
    allCodes.forEach((element) {
      if (element.code!.contains(content) ||
          element.introduce!.contains(content)) {
        codes.add(element);
      }
    });
  }

  copy(String code) async {
    await copyToClipboard(code);
  }
}
